from cleardisk import cleardisk
from flask import request
from anytools.log_part import log_init
import logging
import subprocess
import json

@cleardisk.route('/recure', methods=["GET", "POST"])
def disk_recure():
    alarm_info = str(request.data, encoding="utf-8")
    alarm_info = json.loads(alarm_info)
    log_init("disk_clear.log") # 日志部分
    ip = alarm_info['endpoint']
    for alarm_detail in alarm_info['detail']:
        mount = alarm_detail['tags']['mount']
        if mount == "/data":
            subprocess.getstatusoutput('grep -ri {0} /data/app/recure/host_recure; if [ $? -ne 0 ];then echo {0} >> /data/app/recure/host_recure; fi'.format(ip))
            # 读取/data/app/cleardisk/disk.ini文件中的配置
            status, output = subprocess.getstatusoutput('ansible -i /data/app/recure/host_recure {0} -m shell -a "cat /data/app/cleardisk/disk.ini|grep delete|grep -v \'#\'"'.format(ip))
            if status == 0:
                disk_ini = output.split("\n")[1:]
                for ini in disk_ini:
                    ini = ini.split()
                    time_cycle = "+"+str(int(ini[1][:-1]) - 1)
                    file_path = ini[2]
                    file_name = ini[3]
                    print(time_cycle, file_path, file_name)
                    do_sta, do_out = subprocess.getstatusoutput('ansible-playbook -i /data/app/recure/host_recure -l {0} /data/app/recure/cleardisk/cleardisk.yaml -t /data_recure -e file_path={1} -e file_name={2} -e time_cycle={3}'.format(ip, file_path, file_name, time_cycle))
                    if status == 0:
                        logging.info('DISK 机器{0}执行清理{1}下{2}天前名字包含{3}的文件，成功'.format(ip, file_path, file_name, time_cycle))
                    else:
                        logging.warning('DISK 机器{0}磁盘清理操作执行失败，原因如下:\n{1}'.format(ip, do_out))
            else:
                logging.warning('DISK 机器{0}没有获取到相关磁盘清理配置，原因如下:\n{1}'.format(ip, output))
                    # 删除文件
    return 'ok'
